﻿using System.IO;
using System.Linq;
using Castle.DynamicProxy;
using HardMock.Domain;
using HardMock.Recording;

namespace HardMock
{
    class RecorderAspect : IInterceptor
    {
        private readonly IRepository repository;
        private readonly IIdentifierFactory identifierFactory;
        private readonly IMethodCallFactory methodCallFactory;

        internal RecorderAspect(IRepository repository, IIdentifierFactory identifierFactory, IMethodCallFactory methodCallFactory)
        {
            this.repository = repository;
            this.identifierFactory = identifierFactory;
            this.methodCallFactory = methodCallFactory;
        }

        public void Intercept(IInvocation invocation)
        {
            var methodCall = methodCallFactory.Create(invocation);

            var identifier = identifierFactory.Create(methodCall);

            invocation.Proceed();

            repository.Update(identifier, new CallResult(invocation.ReturnValue, methodCall.Arguments.ToList()));
        }

        public void Serialize(Stream stream)
        {
            repository.Serialize(stream);

            if (stream is MemoryStream)
            {
                stream.Seek(0, SeekOrigin.Begin);
            }
        }
    }
}